import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../../common/api/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/values/index.dart';
import '../../im/im_chat/index.dart';
import 'index.dart';

class PersonController extends GetxController {
  PersonController();

  final state = PersonState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final map = Get.arguments;
    if (map != null && map["id"] != null && map["id"] is String) {
      String id = map["id"] as String;
      loadPersonInfo(id);
    } else {
      OLogger.e('参数异常，没有人员 id');
      Get.back();
    }
    super.onReady();
  }

  /// 查询人员信息
  loadPersonInfo(String id) async {
    Loading.show();
    final person = await OrganizationControlService.to.person(id);
    if (person != null) {
      Loading.dismiss();
      if (person.superior != null && person.superior?.isNotEmpty == true) {
        loadSuperiorName(person.superior!);
      }
      state.person.value = person;
      // 隐藏手机号码
      if (O2ContactPermissionManager.instance.isHiddenMobile(person.distinguishedName!)) {
        person.showMobile = O2.hiddenMobileNumber;
      }
      if (person.woIdentityList != null) {
        state.departmentNames = person.woIdentityList!.map((e) => e.unitName!).toList().join('、');
      }
      state.personAttributeList.addAll(person.woPersonAttributeList??[]);
    } else {
      OLogger.e('人员 id $id 查询人员信息失败！');
      Get.back();
    }
  }
  /// 汇报对象人员名称
  loadSuperiorName(String id ) async {
    final person = await OrganizationControlService.to.person(id);
    if (person != null) {
      state.superiorName = person.name ?? '';
    }
  }
 

  void mailTo(String mail) async {
    if (mail.isNotEmpty) {
      Uri uri = Uri(scheme: 'mailto', path: mail);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri);
      }
    }
  }

  void telTo(String phone) async {
    if (phone.isNotEmpty) {
      Uri uri = Uri(scheme: 'tel', path: phone);
       if (await canLaunchUrl(uri)) {
        await launchUrl(uri);
      }
    }
  }


  /// 发起聊天
  Future<void> startSingleChat( ) async {
    var person = state.person.value;
    if (person != null && person.distinguishedName != null) {
       final conv = await MessageCommunicationService.to.createConversation(O2.imConversationTypeSingle, [person.distinguishedName!]);
      if (conv != null) {
        await ImChatPage.open(conv.id!);
      }
    }
  }

}
